//
//  PermentThread.m
//  线程保活
//
//  Created by 崔博 on 2018/8/30.
//  Copyright © 2018年 崔博. All rights reserved.
//

#import "PermentThread.h"

@interface BBThread : NSThread

@end

@implementation BBThread

- (void)dealloc
{
    NSLog(@"我是线程我挂了%@",self);
}
@end



@interface PermentThread()
@property (nonatomic, strong) BBThread * innerThread;
@property (nonatomic, assign,getter=isStop) BOOL isStop;
@end
@implementation PermentThread

- (instancetype)init
{
    self = [super init];
    if (self) {
        __weak typeof(self) weakself = self;
        self.innerThread = [[BBThread alloc] initWithBlock:^{
            [[NSRunLoop currentRunLoop] addPort:[NSPort new] forMode:NSDefaultRunLoopMode];
            
            while (weakself && !self.isStop) {
                [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
            }
        }];
    }
    return self;
}
- (void)run
{
    [self.innerThread start];
}
- (void)stop
{
    if (!self.innerThread) return;
    [self performSelector:@selector(__stop) onThread:self.innerThread withObject:nil waitUntilDone:YES];
}
- (void)executeTask:(void (^)(void))task
{
    if (!self.innerThread || !task) return;
    [self performSelector:@selector(__excuteTask:) onThread:self.innerThread withObject:task waitUntilDone:NO];
}
#pragma mark - private methods
- (void)__stop
{
    self.isStop = YES;
    CFRunLoopStop(CFRunLoopGetCurrent());
    self.innerThread = nil;
}
- (void)__excuteTask:(void (^)(void))task
{
    task();
}
@end
